/**
* @Description: 销售区域管理
* @author  tangbin
* @date 2023/3/10
*/
<template>
  <div class="app-containers">
    <query-table-render
        ref="queryTable"
        :query-model="queryModel"
        :table-request="requestTableData"
        :table-column="tableColumns"
        :toolbar-render="toolbarRnd"
        :transform-query="transformQuery"
        :title-render="titleRender"
        @on-operator="onOperator"
    >
      <template v-slot:form>
        <el-form-item label="区域名称" prop="name">
          <el-input v-model="queryModel.name" placeholder="请输入" clearable @keyup.enter.native="searchListQuery" />
        </el-form-item>
        <el-form-item label="包含行政区划" prop="salesArea" label-width="140px">
          <el-cascader
            size="small"
            style="width:100%"  
            v-model="queryModel.salesArea"
            :options="areaList"
            :props="propsArea"
            clearable
          />
          <!-- <el-select v-model="queryModel.status" placeholder="请选择" style="width:100%" clearable>
            <el-option
              v-for="item in dict.type.basic_data_sales_region"
              :key="item.value"
              :label="item.label"
              :value="item.value"/>
          </el-select> -->
        </el-form-item>
      </template>
    </query-table-render>


    <!-- 配置行政区划 -->
    <el-dialog :title="title" :visible.sync="open" width="858px" append-to-body :close-on-click-modal="false" @close="cancelDialog">
      <div class="area-main">
        <el-form size="small" ref="form" :model="form" :rules="rules" label-width="82px">
          <el-form-item label="区域名称:" prop="name">
            <el-input
              placeholder="请输入"
              clearable
              v-model="form.name"
              size="small"
              maxlength="100"
            >
            </el-input>
          </el-form-item>
          <el-form-item label="备注:" prop="remark" >
            <el-input v-model="form.remark" :autosize="{ minRows: 2, maxRows: 12}" type="textarea" placeholder="请输入内容" maxlength="500" show-word-limit></el-input>
          </el-form-item>
          <!-- 暂时屏蔽，后面优化功能 -->
          <el-row style="display: flex;" v-if="isAdd == false">
            <el-form-item label="立即生效:" prop="effectiveImmediate">
              <el-radio-group v-model="form.effectiveImmediate" @change="effectiveImmediateChange">
                <el-radio v-for="item in effectOptions" :label="item.value">{{ item.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="生效日期:" prop="validTime" style="margin-left: 40px;" v-if="form.effectiveImmediate == false">
              <el-date-picker
                  v-model="form.validTime"
                  :picker-options="expireTimeOPtion"
                  type="date"
                  format="yyyy/MM/dd"
                  value-format="yyyy-MM-dd"
                  placeholder="日期时间">
              </el-date-picker>
            </el-form-item>
          </el-row>
          <el-form-item label="生效日期:" prop="validTime" v-if="isAdd == true">
            <el-date-picker
                v-model="form.validTime"
                :picker-options="expireTimeOPtion"
                type="date"
                format="yyyy/MM/dd"
                value-format="yyyy-MM-dd"
                placeholder="日期时间">
            </el-date-picker>
          </el-form-item>
          
          <span style="display: inline-block ;height:1px; background-color: #EBEEF5; width: 100%;"></span>
          <div class="area-bottom">
            <div class="dialog-left" v-loading="pageLoading">
              <el-form-item label="地区名称:" style="margin-right: 15px;">
                <el-input
                  placeholder="请输入"
                  clearable
                  v-model="filterText"
                  size="small"
                />
              </el-form-item>
              <el-checkbox style="margin-left: 10px;" v-model="menuExpand" @change="handleCheckedTreeExpand($event, 'menu')">展开/折叠</el-checkbox>
              <div class="left-area">
                <el-tree
                  :data="menuOptions"
                  show-checkbox
                  ref="menu"
                  node-key="id"
                  :check-strictly="false"
                  empty-text="暂无数据"
                  :check-on-click-node="true"
                  :props="defaultProps"
                  @check="treeCheck"
                  :filter-node-method="filterNodeArea"
                ></el-tree>
              </div>
            </div>
            <span class="dialog-mid"></span>
            <div class="dialog-right">
              <span class="right-top">已选地区</span>
              <el-table
                class="right-bottom"
                :data="form.areaList ? form.areaList : []" 
                :inline="true"
                :border="false"

              >
                <el-table-column label="" align="left" prop="areaName" width="408px">
                  <template slot-scope="scope">
                    <div class="table-column-area">
                      <span class="table-column-area-span">{{ scope.row.areaName }}</span>
                      <el-button class="table-column-area-btn" size="mini" type="text" icon="el-icon-circle-close" @click="deleteArea(scope.row)"></el-button>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            
          </div>
          <!-- 显示其他区域已经存在的 -->
          <div class="area-bottom-desc" id="areaDesc">
            <ul style="list-style-type: none; padding-left: 20px; padding-right: 20px; margin-top: 8px; margin-bottom: 8px;">
              <li v-for="item in configAreas" style="display: block; color: #FAAD14; font-size: 14px; font-weight: 400; height:24px; line-height: 24px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">{{ item }}</li>
            </ul>
          </div>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelDialog">取 消</el-button>
        <el-button type="primary" @click="submitForm" :loading="saveloading">确 定</el-button>
      </div>
    </el-dialog>
    
    <!-- 变更记录-->
    <change-record ref="records" />
  </div>
</template>

<script>
import {checkPermi} from '@/utils/permission.js'
import QueryTableRender from "@/components/QueryTableRender";
import dayjs from "dayjs"
import {salesRegionList, addSalesRegion, updateSalesRegion, salesRegionCheckRepeat} from '@/api/basic/salesArea.js'
import {getDivisionTree} from '@/api/basic/orderGoodsClas.js'
import changeRecord from './changeRecord.vue'

export default {
  name: "SalesAreaManage",
  dicts: ['basic_data_division', 'basic_data_sales_region'],
  components: {QueryTableRender,changeRecord},
  data() {
    return {
      queryModel: {}, // 查询参数
      tableColumns: [], // 列表
      saveloading: false,
      pageLoading: false,
      open: false, // 是否显示弹窗
      filterText: '', // 搜索地区
      menuOptions: [], // 所有地区列表列表
      areaList: [], // 当前的地区
      menuExpand: false, // 是否展开折叠
      defaultProps: {
        children: "children",
        label: "name"
      },
      effectOptions: [{label: '是(不生成新版本)', value: true}, {label: '否', value: false}], // 立即生效options
      propsArea: {label: 'name', value: 'id', children: 'children', checkStrictly: true},
      configAreas: [], // 已经配置过的地区
      title: '', // 弹窗标题
      isAdd: false,
      form: {
        name: undefined, // 区域名称
        remark: undefined, // 备注
        effectiveImmediate: false, // 立即生效
        validTime: undefined, // 生效日期
        areaList: [], // 行政区划
      },
      rules: {
        name: [
          {required: true, message: "请输入区域名称", trigger: "blur"}
        ],
        effectiveImmediate: [
          {required: true, message: "请选择是否立即生效", trigger: "change"}
        ],
        validTime: [
          {required: true, message: "请选择生效日期", trigger: "change"}
        ]
      },
      expireTimeOPtion: {
        disabledDate(time) {
          return time.getTime() < Date.now() //如果没有后面的-8.64e7就是不可以选择今天的
        },
      },
    }
  },
  created() {
    this.setupQueryModel();
    this.setupTableColumns();
  },
  mounted() {
    // this.getDivisionTree();
  },
  watch: {
    $route(route) {
      // console.log('name', route.name);
      if (route.name == 'GoodsPrices') {
        this.onRefreshTable();
      }
    },
    filterText(val) {
      this.$refs.menu.filter(val);
    }
  },
  methods: {
    /**
     * 初始化查询参数
     */
     setupQueryModel() {
      this.queryModel = {
        name: undefined, // 区域名称
        salesArea: [], // 包含行政区划
      };
    },

    setupTableColumns() {
      this.tableColumns = [
        {
          label: '序号',
          width: '60',
          type: 'index',
          increment: true
        },
        {
          prop: 'code',
          label: '区域编码',
          minWidth: '150',
        },
        {
          prop: 'name',
          label: '区域名称',
          minWidth: '160',
          showOverflowTooltip: true,
        },
        {
          prop: 'showAreas',
          label: '包含行政区划',
          align: 'left',
          minWidth: '150',
          // showOverflowTooltip: true,
          render:(h, text, {record}) => {
            let list = [];
            record.areaList && record.areaList.forEach((item) => {
              list.push(h('li', {style:'height: 22px; line-height: 22px; font-size: 14px; font-weight: 400;'}, item.areaName));
            });
            return h('el-tooltip', {props: {placement: 'top'}}, [
              h('div', {slot: 'content', style: 'min-width: 160px; max-height:236px; overflow: auto;'}, [
                h('ul', {style: 'list-style-type: none; padding-left:0;'}, list)
              ]),
              h('span', {style: 'overflow: hidden; text-overflow: ellipsis; white-space: nowrap;'}, record.showAreas && record.showAreas.slice(0, 15))
            ]);
          }
        },
        {
          prop: 'remark',
          label: '备注',
          minWidth: '180',
          align: 'left',
          showOverflowTooltip: true,
          // render: (h, text) => {
          //   return text+'%';
          // }
        },
        {
          label: '操作',
          width: '150',
          type: 'operator',
          align: "left",
          fixed: 'right',
          operators: record => { return this.operatorsFunc(record)}
        },
        
      ];
    },

    /**
     * 搜索列表查询
     */
     searchListQuery() {
      this.$refs['queryTable'].submitQuery();
    },

    /**
     * 查询列表
     * @param {*} queryParams 
     */
     async requestTableData(queryParams) {

      let resData = await this.getSalesRegionList(queryParams);
      let areaData = await this.getDivisionTree();
      // console.log('resData=', resData);
      if (areaData.code == 200) {
        /*
        areaCode: id,  // 当前选择的
        level: level,
        parentId: parentId, // 当前的父级
        areaName: name,   // 组装的名称
        provinceCode: area.area1 ? area.area1.id : undefined,
        cityCode: area.area2 ? area.area2.id : undefined,
        districtCode: area.area3 ? area.area3.id : undefined,
        */
        
        let list = resData.data;
        if (list && list.length > 0) {
          list.forEach((ent, index) => {
            // console.log('-----------------', index);
            // console.log('ent=', ent);
            ent.areaList && ent.areaList.forEach((item, i) => {
              // console.log('item=', item);
              // console.log('*************************=', i);
              let provinceObj = undefined; // 省
              let cityObj = undefined; // 市
              let districtObj = undefined; // 区县
              if (item.provinceCode && item.provinceCode.length > 0) {
                provinceObj = this.getAreaNodeData(item.provinceCode);
                // console.log('省份结束');
              }
              if (item.cityCode && item.cityCode.length > 0) {
                cityObj = this.getAreaNodeData(item.cityCode);
                // console.log('城市结束');
              }
              if (item.districtCode && item.districtCode.length > 0) {
                districtObj = this.getAreaNodeData(item.districtCode);
                // console.log('item.districtCode结束=', item.districtCode);
              }
              // console.log('provinceObj=', provinceObj);
              // console.log('cityObj=', cityObj);
              // console.log('districtObj=', districtObj);
              if (districtObj) {
                this.$set(item, 'areaCode', districtObj.id);
                this.$set(item, 'level', districtObj.level);
                this.$set(item, 'parentId', districtObj.parentId);
                this.$set(item, 'areaName', provinceObj.name + '-' + cityObj.name + '-' + districtObj.name);
                // item = {
                //   ...item,
                //   areaCode: districtObj.id,  // 当前选择的
                //   level: districtObj.level,
                //   parentId: districtObj.parentId, // 当前的父级
                //   areaName: provinceObj.name + '-' + cityObj.name + '-' + districtObj.name,   // 组装的名称
                // };
              }
              else if (cityObj) {
                this.$set(item, 'areaCode', cityObj.id);
                this.$set(item, 'level', cityObj.level);
                this.$set(item, 'parentId', cityObj.parentId);
                this.$set(item, 'areaName', provinceObj.name + '-' + cityObj.name);
                // item = {
                //   ...item,
                //   areaCode: cityObj.id,  // 当前选择的
                //   level: cityObj.level,
                //   parentId: cityObj.parentId, // 当前的父级
                //   areaName: provinceObj.name + '-' + cityObj.name,   // 组装的名称
                // };
              } else if (provinceObj) {
                this.$set(item, 'areaCode', provinceObj.id);
                this.$set(item, 'level', provinceObj.level);
                this.$set(item, 'parentId', provinceObj.parentId);
                this.$set(item, 'areaName', provinceObj.name);
                // item = {
                //   ...item,
                //   areaCode: provinceObj.id,  // 当前选择的
                //   level: provinceObj.level,
                //   parentId: provinceObj.parentId, // 当前的父级
                //   areaName: provinceObj.name,   // 组装的名称
                // };
              }
            });
            

            
            let showAreas = undefined;
            let arr = [];
            let idx = 0;
            ent.areaList && ent.areaList.some((item) => {
              if (idx >= 5) {
                return true;
              }
              arr.push(item.areaName);
              idx = idx + 1;
            });
            // console.log('arr=', arr);
            showAreas = arr.toString();
            // console.log('showAreas=', showAreas);
            this.$set(ent, 'showAreas', showAreas);
            // console.log('ent=', ent);
          });
        }
        
        // console.log('resData=', resData);
        return resData;
      } else {
        return {
          success: true,
          total: 0,
          data: [],
        }
      }
    },

    /**
     * 获取销售区域列表
     * @param {*} queryParams 
     */
    async getSalesRegionList(queryParams) {
      let resData = {
        success: true,
        total: 0,
        data: [],
      };
      if (queryParams.salesArea && queryParams.salesArea.length > 0) {
        if (queryParams.salesArea.length == 1) {
          queryParams.provinceCode = queryParams.salesArea[0];
        } else if (queryParams.salesArea.length == 2) {
          queryParams.provinceCode = queryParams.salesArea[0];
          queryParams.cityCode = queryParams.salesArea[1];
        } else if (queryParams.salesArea.length == 3) {
          queryParams.provinceCode = queryParams.salesArea[0];
          queryParams.cityCode = queryParams.salesArea[1];
          queryParams.districtCode = queryParams.salesArea[2];
        }
      }
      await salesRegionList(queryParams).then(respData => {
       let list = [];
       let total = 0;
       if (respData.code == 200) {
        list = respData.data.records;
        total = respData.data.total;
       }
        resData = {
          success: true,
          total: total,
          data: list,
        };
      });
      return resData;
    },


    /**
     * 刷新列表
     */
    onRefreshTable(){
      this.$refs['queryTable'].refreshTable()
    },

    toolbarRnd(h){
      let list = [];
      if (checkPermi(['basic-data:sales-region:add'])) {
        list.push(<el-button type="primary" icon="el-icon-plus" vOn:click={() => this.onAddArea()}>新增区域</el-button>);
      }
      return list;
    },

    transformQuery(queryData) {
      let transParams = {}
      for (let keyName in queryData) {
        if (queryData.hasOwnProperty(keyName)) {
          // if (keyName === 'createTimeRange') {
          //   if(queryData['createTimeRange'] && queryData['createTimeRange'].length){
          //     const [start, end] =  queryData[keyName]
          //     transParams['startTime'] = dayjs(start).startOf('day').format("YYYY-MM-DD HH:mm:ss")
          //     transParams['endTime'] = dayjs(end).endOf('day').format("YYYY-MM-DD HH:mm:ss")
          //   }
          // } else {
            transParams[keyName] = queryData[keyName]
          // }
        }
      }
      return transParams
    },

    titleRender(h) {
      return <div>
        <span style="display:inline-block; background-color: #1890FF;margin-bottom: -2px; margin-right: 8px; width: 3px; height: 14px"></span>
        <span style="display: inline-block; color: #333333; font-size: 16px;">商品价格</span>
      </div>;
    },

    /**
     * 功能列表
     */
     operatorsFunc(row) {

        let list = [];
        if (checkPermi(['basic-data:sales-region:update'])) {
          list.push({label: '修改', command: 'edit'});
        }
        if (checkPermi(['basic-data:sales-region:records'])) {
          list.push({label: '变更记录', command: 'records'});
        }
        return list;  
      },

    /**
     * 操作页面
     * @param {*} command 
     * @param {*} record 
     */
     onOperator(command, record) {
      console.log('11111', command,record)
      record.effectiveImmediate = false
      record.validTime = ""
      if (command == 'edit') {
        this.form = JSON.parse(JSON.stringify(record));
        // this.areaList = JSON.parse(JSON.stringify(row.areaList));
        this.title = '修改销售区域';
        this.isAdd = false;
        this.open = true;
        this.configAreas = [];
        this.$nextTick(()=>{
          this.$refs.menu.setCheckedKeys([]);
        });
        if (this.form.areaList && this.form.areaList.length > 0) {
          this.form.areaList.forEach((item) => {
            this.$nextTick(()=>{
              this.$refs.menu.setChecked(item.areaCode, true ,true);
            });
          });
        }
      }else if(command == 'records'){
        this.$refs.records.show(record);
      }
    },

    /**
     * 新增区域
     */
    onAddArea() {
      this.title = '新增销售区域';
      this.isAdd = true;
      this.configAreas = [];
      this.open = true;
      this.$nextTick(()=>{
        this.$refs.menu.setCheckedKeys([]);
      });
    },

    /**
     * 获取行政区划数据
     */
     getDivisionTree() {
      return getDivisionTree({name: ''}).then(res => {
        // console.log('地区=', res);
        if (res.code === 200) {
          const list = res.data;
          if (list && list.length > 0) {
            this.areaList = JSON.parse(JSON.stringify(res.data[0].children));
            this.menuOptions = list[0].children;
            // console.log('menuOptions=', this.menuOptions);
            this.menuOptions && this.menuOptions.forEach(item => {
              // 子集的数量
              // console.log('item=', item);
              // 省下面有多少个市
              this.$set(item, 'childrenCount', item.children ? item.children.length : 0);
              // console.log('name=', item.name);
              // 遍历市
              item.children && item.children.forEach(ent => {
                this.$set(ent, 'childrenCount', ent.children ? ent.children.length : 0);
              });
            });
          }
        }
        return res;
      }).catch(err => {
        return err;
      });
    },

    cancelDialog() {
      this.open = false;
      this.saveloading = false;
      this.pageLoading = false;
      this.filterText = undefined;
      this.resetFormData(); // 重置
      if (this.isAdd) {
        // this.resetFormData(); // 重置
      } else {
        // this.form.areaList = JSON.parse(JSON.stringify(this.areaList));
      }
      this.handleCheckedTreeExpand(false, 'menu');
    },

    /**
     * 立即生效选择
     */
    effectiveImmediateChange(val) {
      this.form.validTime = undefined;
    },

    /**
     * 重置
     */
    resetFormData() {
      this.form = {
        name: undefined, // 区域名称
        remark: undefined, // 备注
        areaList: [], // 行政区划
      };
    },

    /**
     * 弹窗点击确认
     */
     submitForm() {

      // console.log('form=', this.form);
      // return;
      if (this.form.areaList && this.form.areaList.length <= 0) {
        this.$modal.msgWarning('已选地区不能为空！');
        return;
      }

      
      this.$refs['form'].validate(valid => {
        if (!valid) {
          this.saveloading = false;
          return;
        }
        this.saveloading = true;
        // console.log('isAdd=', this.isAdd);
        // return;
        if (this.isAdd) {
          this.addSalesRegion();
        } else {
          this.updateSalesRegion();
        }
      });

      // this.open = false;
      // this.currentRow.areaList = this.areaList;
      // this.form.receiveArea = undefined;
      // this.areaList = [];
      // console.log('this.currentRow.areaList=', this.currentRow.areaList);
      // return;
      // let list = [];
      // if (this.form.areaList && this.form.areaList.length > 0) {
      //   let index = 0;
      //   this.form.areaList.some((item) => {
      //     if (index >= 5) {
      //       return true;
      //     }
      //     list.push(item.areaName);
      //     index = index + 1;
      //   });
      //   this.form.receiveArea = list.toString();
      // }


      // this.handleCheckedTreeExpand(false, 'menu');
    },

    /**
     * 新增
     */
    addSalesRegion() {
      addSalesRegion(this.form).then(res => {
        // console.log('res=', res);
        if (res.code == 200) {
          // this.areaList = [];
          this.$modal.msgSuccess('新增销售区域成功！');
          this.open = false;
          this.resetFormData(); // 重置
          this.handleCheckedTreeExpand(false, 'menu');
          this.filterText = undefined;
          this.onRefreshTable();
        } else {
          this.$modal.msgError('新增销售区域失败！');
        }
        this.saveloading = false;
      }).catch(err => {
        this.saveloading = false;
      });
    },

    /**
     * 修改
     */
    updateSalesRegion() {

      // console.log('form=', this.form);
      // return;
      updateSalesRegion(this.form).then(res => {
        console.log('res=', res);
        if (res.code == 200) {
          // this.areaList = [];
          this.$modal.msgSuccess('修改销售区域成功！');
          this.open = false;
          this.resetFormData(); // 重置
          this.filterText = undefined;
          this.handleCheckedTreeExpand(false, 'menu');
          this.onRefreshTable();
        } else {
          this.$modal.msgError('修改销售区域失败！');
        }
        this.saveloading = false;
      }).catch(err => {
        this.saveloading = false;
      });
    },

    /**
     * 
     * 过滤属性结构的数据
     * @param {*} value 
     * @param {*} data 
     */
     filterNodeArea(value, data) {
      if (!value) {
        return true;
      }
      return data.name.indexOf(value) !== -1;
    },

    /**
     * 树权限（展开/折叠）
     * @param {*} value 
     * @param {*} type 
     */
     handleCheckedTreeExpand(value, type) {
      if (type == 'menu') {
        let treeList = this.menuOptions;
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value;
        }
      }
    },

    /**
     * 点击tree
     * @param {*} item 
     * @param {*} de 
     */
     async treeCheck(item, data) {
      
      // this.$set(item, 'v-loading', true);
      console.log('点击item=', item);
      let selected = false; // 是否选中
      if (data.checkedKeys.indexOf(item.id) !== -1) {
        // console.log('选中');
        selected = true;
      }

      if (selected == false) {
        this.unselectedNode(item);
        return;
      }
      this.pageLoading = true;
      
      const resArea = this.checkParentLevel(item, data);
      // console.log('resArea=', resArea);
      const resData = await this.getSalesRegionCheckRepeat(this.form.id ? this.form.id : undefined, resArea.area1 ? resArea.area1.id: undefined, resArea.area2 ? resArea.area2.id: undefined, resArea.area3 ? resArea.area3.id : undefined);
      setTimeout(() => {
          this.pageLoading = false;
        }, 1000);
      // console.log('点击了');
      // console.log('resData=', resData);
      // this.$set(item, 'disabled', false);
      // console.log('resArea=', resArea);
      let ret = false;
      if (resData.code == 200 && resData.data && resData.data.length > 0) {
        let list = resData.data;
        list.forEach(name => {
          if (this.configAreas.indexOf(name) !== -1) {
            this.configAreas.splice(this.configAreas.indexOf(name), 1);
          }
          this.configAreas.push(name);
        });
        ret = true;
        // console.log('list =', list);
      }
      console.log('当前级别=', resArea.currentLevel, '; 总级别=', resArea.totalLevel);
      let model = undefined;
      if (resArea.currentLevel == resArea.totalLevel) { // 当前层级 跟总层级相等 表示 叶子节点
        // 当前层级跟总层级数一样
        model = this.currentEqualTotalLevel(item, resArea);
      } else if (resArea.currentLevel == resArea.totalLevel - 1) { // 倒数第二级
        model = this.currentEqualTotalLevelTwo(item, resArea);
      } else if (resArea.currentLevel == resArea.totalLevel - 2) { // 倒数第三极
        model = this.currentEqualTotalLevelOne(item, resArea);
      }


      // this.pageLoading = false;
      if (model) {
        if (ret == true) {
          this.$modal.msgWarning('此地区在区域中已配置过！');
          // this.$nextTick(()=>{
          //   this.$refs.menu.setChecked(model.areaCode, false ,true);
          // });
        }
        this.addArea(model);

        let areaDesc = document.getElementById('areaDesc');
        // console.log('areaDesc=', areaDesc);
        this.$nextTick(() => {
          areaDesc.scrollTop = areaDesc.scrollHeight;
        });
        
      }
     },

     /**
      * 销售区域重复校验
      */
     getSalesRegionCheckRepeat(id, provinceCode, cityCode, districtCode) {
      let params = {
        id: id,
        provinceCode: provinceCode,
        cityCode: cityCode,
        districtCode: districtCode
      };
      // console.log('paams=', params);
      return salesRegionCheckRepeat(params).then(res => {
        // this.pageLoading = false;
        // setTimeout(() => {
        //   this.pageLoading = false;
        // }, 1000);
        return res;
      }).catch(err => {
        // this.pageLoading = false;
        // setTimeout(() => {
        //   this.pageLoading = false;
        // }, 1000);
        return err;
      });
     },

     /**
     * 取消选中节点
     */
    unselectedNode(item) {
      console.log('------取消选中节点-=', item);
      if (item.level == 1) { // 当前节点是一级
        if (item.childrenCount == 0) { // 没有子集，比如 香港
          this.removeCheckedArea(item.id);
        } else {
          item.children && item.children.forEach(model => {
            let list = this.form.areaList.filter(ent => {
              if (model.id == ent.areaCode) {
                return ent;
              }
            });
            if (list && list.length > 0) {
              this.removeCheckedArea(list[0].areaCode);
            }
            model.children && model.children.forEach(ent => {
              let list = this.form.areaList.filter(e => {
                if (ent.id == e.areaCode) {
                  return e;
                }
              });
              if (list && list.length > 0) {
                this.removeCheckedArea(list[0].areaCode);
              }
            });
          });
          this.removeCheckedArea(item.id);
        }
      } else if (item.level == 2) { // 当前节点是二级
        console.log('cur=', item);
        // 根据父节点id得到父节点选中的子节点的个数
        const count = this.getChildCount(item.parentId);
        console.log('count=====', count);
        if (count == 0) {// 表示没有子节点 或者 选中了所有的子节点
          const parentItem = this.getAreaNodeData(item.parentId); // 获取父节点信息
          console.log('当前是二级=', count, '; total=', parentItem.childrenCount);
          let selectedNode = this.getSelectedNodeData(item.parentId);
          console.log('查找上级=', selectedNode);
          if (selectedNode) {
            // 找到了父级，表示子集是全选
            this.removeCheckedArea(item.parentId);
            parentItem.children.forEach(ent => {
              if (ent.id !== item.id) {
                let model = {
                  areaCode: ent.id, 
                  parentId: ent.parentId, 
                  areaName: parentItem.name + '-' + ent.name,
                  districtCode: undefined, // 区县
                  cityCode: ent.id, // 城市
                  provinceCode: ent.parentId, // 省份
                };
                this.addArea(model);
              }
            });
          } else {
            if (item.children && item.children.length > 0) {
              item.children.forEach(ent => {
                // console.log('删除=', ent.id + '-'+ent.name);
                this.removeCheckedArea(ent.id);
              });
            }
            this.removeCheckedArea(item.id);
          }
        } else {
          if (item.children && item.children.length > 0) {
            // console.log('有子');
            item.children.forEach(ent => {
              // console.log('删除=', ent.id + '-'+ent.name);
              this.removeCheckedArea(ent.id);
            });
          }
          this.removeCheckedArea(item.id);
          
        }
      } else if (item.level == 3) {
        console.log('cur=', item);
        const count = this.getChildCount(item.parentId); // 三级的父级(二级)
        if(count !== 0) {
          this.removeCheckedArea(item.id);
          return;
        }
        console.log('count =', count);
        const parentTwoItem = this.getAreaNodeData(item.parentId); // 获取父节点信息(二级)
        const parentFirstItem = this.getAreaNodeData(parentTwoItem.parentId); // 一级
        console.log('parentTwoItem=', parentTwoItem);
        console.log('parentFirstItem=', parentFirstItem);
        let selectedNode = this.getSelectedNodeData(parentFirstItem.id); // 一级有没有被选中
        if (selectedNode) { // 一级被选中了
          console.log('一级被选中了');
          this.removeCheckedArea(parentFirstItem.id);
          parentFirstItem && parentFirstItem.children.forEach(ent => {
            // console.log('===ent', ent);
            if (ent.id !== parentTwoItem.id) {
              let model = {
                areaCode: ent.id, 
                parentId: ent.parentId, 
                areaName: parentFirstItem.name + '-' + ent.name,
                districtCode: undefined,
                cityCode: ent.id,
                provinceCode: ent.parentId
              };
              this.addArea(model);
            }
          });
          parentTwoItem && parentTwoItem.children.forEach(ent => {
            // console.log('===ent', ent);
            if (ent.id !== item.id) {
              let model = {
                areaCode: ent.id, 
                parentId: ent.parentId, 
                areaName: parentFirstItem.name + '-' + parentTwoItem.name + '-' + ent.name,
                districtCode: ent.id,
                cityCode: ent.parentId,
                provinceCode: parentTwoItem.parentId
              };
              this.addArea(model);
            }
          });
        } else { // 一级没有被选中
          // console.log('一级没有被选中');
          let selectedNode = this.getSelectedNodeData(parentTwoItem.id); // 一级有没有被选中
          if (selectedNode) {
            this.removeCheckedArea(parentTwoItem.id);
            parentTwoItem && parentTwoItem.children.forEach(ent => {
            if (ent.id !== item.id) {
              let model = {
                areaCode: ent.id, 
                parentId: ent.parentId, 
                areaName: parentFirstItem.name + '-' + parentTwoItem.name + '-' + ent.name,
                districtCode: ent.id,
                cityCode: ent.parentId,
                provinceCode: parentTwoItem.parentId
              };
              this.addArea(model);
            }
          });
          }
        }
      }
    },

    /**
     * 当前层级等总层级
     * @param {*} curRow 当前点击的节点
     * @param {*} area 
     */
    currentEqualTotalLevel(curRow, area) {
      console.log('当前层级等总层级');
      // console.log('curRow=', curRow);
      // console.log('area=', area);
      let name = '';
      let id = undefined;
      let parentId = undefined;
      let level = undefined;
      if (curRow.level == 1) {
        console.log('当前层级是1');
        name = area.name1;
        id = area.area1.id;
        level = area.area1.level;
        parentId = area.area1.parentId;
      } else if (curRow.level == 2) {
        console.log('当前层级是2');
        name = area.name1;
        const count = this.getChildCount(curRow.parentId) + 1;
        if (area.area1.childrenCount == count) { // 表示选中的父级中的所有子集
          console.log('表示选中的父级中的所有子集=', area);
          this.removeChildrenNode(curRow.parentId);
          id = curRow.parentId;
          level = area.area1.level;
          parentId = area.area1.parentId;
          area.area2 = undefined;
        } else {
          name = name + '-' + area.name2;
          id = curRow.id;
          level = curRow.level;
          parentId = curRow.parentId;
        }
        // console.log('count =', count);
      } else if (curRow.level == 3) {
        console.log('当前层级是3');
        const districtCount = this.getChildCount(curRow.parentId) + 1; // 区县数量
        // console.log('districtCount=', districtCount);
        if (districtCount == area.area2.childrenCount) {
          // 选中了，某个城市的所有区县
          console.log('选中了，某个城市的所有区县');
          area.area3 = undefined; // 当选中了所有的区县 设置为空
          const cityCount = this.getChildCount(area.area2.parentId) + 1;
          if (cityCount == area.area1.childrenCount) {
            // 选中了所有的城市
            console.log('选中了所有的城市');
            this.unselectedNode(area.area1);
            name = area.name1;
            id = area.area1.id;
            level = area.area1.level;
            parentId = area.area1.parentId;
            area.area2 = undefined; // 选中了所有的市 设置为空
          } else {
            console.log('55555');
            this.removeChildrenNode(curRow.parentId);
            name = area.name1 + '-' + area.name2;
            id = area.area2.id;
            level = area.area2.level;
            parentId = area.area2.parentId;
            area.area3 = undefined;
          }
        } else {
          // console.log('不是全部');
          name = area.name1 + '-' + area.name2 + '-' + area.name3;
          id = curRow.id;
          level = curRow.level;
          parentId = curRow.parentId;
        }
      }
      let model = {
        areaCode: id, 
        level: level,
        parentId: parentId, 
        areaName: name,
        provinceCode: area.area1 ? area.area1.id : undefined,
        cityCode: area.area2 ? area.area2.id : undefined,
        districtCode: area.area3 ? area.area3.id : undefined,
      };
      console.log('model=', model);
      return model;
      
      // this.addArea(model);
    },

    /**
     * 当前层级跟总层级相差1
     * @param {*} curRow 
     * @param {*} area 
     */
    currentEqualTotalLevelTwo(curRow, area) {
      console.log('当前层级跟总层级相差1');
      // console.log('curRow=', curRow);
      // console.log('area=', area);
      let name = '';
      let id = undefined;
      let level = undefined;
      let parentId = undefined;

      const count = this.getChildCount(curRow.parentId) + 1;
      // console.log('count=', count);
      if (area.area1.childrenCount == count) {
        // 选中了所有城市
        // console.log('选中了所有城市');
        this.unselectedNode(area.area1);
        // this.removeChildrenNode(curRow.parentId);
        id = area.area1.id;
        level = area.area1.level;
        parentId = area.area1.parentId;
        name = area.name1;
        area.area2 = undefined;
        area.area3 = undefined;
      } else {
        // 未选中所有城市
        this.unselectedNode(curRow);
        id = curRow.id;
        level = curRow.level;
        parentId = curRow.parentId;
        if (area.name2 && area.name2.length > 0) {
          name = area.name1 + '-' + area.name2;
        }
        else {
          name = area.name1;
        }
      }

      let model = {
        areaCode: id, 
        level: level,
        parentId: parentId, 
        areaName: name,
        provinceCode: area.area1 ? area.area1.id : undefined,
        cityCode: area.area2 ? area.area2.id : undefined,
        districtCode: area.area3 ? area.area3.id : undefined,
      };
      // console.log('model=', model);
      // this.addArea(model);
      return model;
    },

    /**
     * 当前层级跟总层级相差2
     * @param {*} curRow 
     * @param {*} area 
     */
     currentEqualTotalLevelOne(curRow, area) {
      console.log('当前层级跟总层级相差2');
      // console.log('curRow=', curRow);
      // console.log('area=', area);
      let name = curRow.name;
      let id = curRow.id;
      let level = curRow.level;
      let parentId = curRow.parentId;
      curRow.children && curRow.children.forEach(item => {
        let list = this.form.areaList.filter(ent => {
          if (item.id == ent.areaCode) {
            return ent;
          }
        });
        if (list && list.length > 0) {
          this.removeCheckedArea(list[0].areaCode);
        }
        item.children && item.children.forEach(ent => {
          let list = this.form.areaList.filter(e => {
            if (ent.id == e.areaCode) {
              return e;
            }
          });
          if (list && list.length > 0) {
            this.removeCheckedArea(list[0].areaCode);
          }
        });
      });
      let model = {
        areaCode: id,  // 当前选择的
        level: level,
        parentId: parentId, // 当前的父级
        areaName: name,   // 组装的名称
        provinceCode: area.area1 ? area.area1.id : undefined,
        cityCode: area.area2 ? area.area2.id : undefined,
        districtCode: area.area3 ? area.area3.id : undefined,
      };
      // console.log('model=', model);
      // this.addArea(model);
      return model;
    },

    /**
     * 根据地区id获取地区数据
     * @param {*} id 
     */
    getAreaNodeData(id) {
      // console.log('进来了id=', id);
      // console.log('this.menuOptions=', this.menuOptions);
      // 有没有查询到省份
      let list = this.menuOptions && this.menuOptions.filter(e => {
        // console.log('e.id=', e.id, '; id=', id);
        if (e.id == id) {
          return e;
        }
      });
      // console.log('22222222');
      // console.log('list=', list);
      let arr = [];
      if (this.menuOptions && list && list.length == 0) {
        // console.log('11111');
        this.menuOptions.some(item => {
          arr = item.children && item.children.filter(e => {
            if (e.id == id) {
              // console.log('id=', id, '; e=', e);
              return e;
            }
          });
          
          if (arr && arr.length > 0) {
            // console.log('666666');
            return true;
          } else {
            
          }
          // console.log('888888');
          
        });
        // let arr = this.menuOptions.children && this.menuOptions.children.filter(e => {
        //   console.log('id1=', e.id, 'id=', id);
        //   if (e.id == id) {
        //     return e;
        //   }
        // });
        // console.log('arr=', arr);
        // console.log('99999999');
        if (arr && arr.length > 0) {
          return arr[0];
        } else {
          // console.log('没有找到=', id);
          let ret = false;
          arr = [];
          if (this.menuOptions && this.menuOptions.length > 0) {
            this.menuOptions.some(prov => {
              prov.children && prov.children.some(cityObj => {
                // console.log('name=', cityObj.name);
                arr = cityObj.children && cityObj.children.filter(e => {
                  if (e.id == id) {
                    // console.log('找到了鹅鹅鹅id=', id, '; e=', e);
                    ret = true;
                    return e;
                  }
                });
                // console.log('arr====', arr);
                return ret;
              });
              // console.log('909090909');
              return ret;

            });
            // console.log('5656565656=', arr);
            if (arr && arr.length > 0) {
              // console.log('有了==', arr[0]);
              return arr[0];
            } else {
              return undefined;
            }
          }
          return undefined;
        }
      } else {
        // console.log('4444444');
        if (list && list.length > 0) {
          return list[0];
        } else {
          return undefined;
        }
      }
    },

    /**
     * 根据父节点id得到父节点选中的子节点的个数
     * @param {*} parentId 
     */
    getChildCount(parentId) {
      const list = this.form.areaList.filter(e => {
        if (e.parentId == parentId) {
          return e;
        }
      });
      return list && list.length;
    },

    /**
     * 得到选中节点
     * @param {*} id 
     */
    getSelectedNodeData(id) {
      // console.log('id=', id);
      const list = this.form.areaList.filter(e => {
        // console.log('e.areacode=', e.areaCode , 'id=', id);
        if (e.areaCode == id) {
          return e;
        }
      });
      // console.log('list=', list);
      if (list && list.length > 0) {
        return list[0];
      }
      return undefined;
    },

    /**
     * 删除子节点数据
     * @param {*} parentId 
     */
    removeChildrenNode(parentId) {
      this.form.areaList = this.form.areaList.filter(e => {
        if (e.parentId != parentId) {
          return e;
        }
      });
    },


    /**
     * 添加地区
     * @param {*} item 
     */
    addArea(item) {
      // console.log('添加item=', item);
      const newList = this.form.areaList.filter(e => {
        if (e.areaCode == item.areaCode) {
          return e;
        }
      });
      if (!newList ||newList.length == 0) {
        this.form.areaList.push(item);
      }
    },

    /**
     * 从已经选中的区域 删除
     * @param {*} code 
     */
    removeCheckedArea(code) {
      let model = null;
      this.form.areaList.some((item) => {
        if (item.areaCode === code) {
          model = item;
          return true;
        }
      });
      if (model !== null) {
        // console.log('找到了数据');
        this.form.areaList.splice(this.form.areaList.indexOf(model), 1);
      }
    },

    /**
     * 从列表中删除
     * @param {*} row 
     */
    deleteArea(row) {
      this.removeCheckedArea(row.areaCode);
      this.$nextTick(()=>{
        this.$refs.menu.setChecked(row.areaCode, false ,true);
      });
    },

    /**
     * 根据当晚地区id 获取的相关参数
     * @param {*} curId 
     * @param {*} data 
     */
    checkParentLevel(row, data) {
      let curId = row.id;
      let name1 = ''; // 一级名称
      let area1 = undefined; // 一级对象
      let name2 = ''; // 二级名称
      let area2 = undefined; // 二级对象
      let name3 = ''; // 三级名称
      let area3 = undefined; // 三级级对象
      let totalLevel = 0; // 总级别
      let currentLevel = 0; // 当前级别
      let direcCities = ['北京市', '上海市', '天津市', '重庆市'];

      if (row.level == 3) { // 当前层级是3级
        currentLevel = row.level;
        totalLevel = row.level;
        let twoItem = this.getAreaNodeData(row.parentId);
        let oneItem = undefined;
        if (twoItem) {
          oneItem = this.getAreaNodeData(twoItem.parentId);
        }
        name1 = oneItem && oneItem.name;
        area1 = oneItem;
        name2 = twoItem && twoItem.name;
        area2 = twoItem;
        name3 = row.name;
        area3 = row;
      } else if (row.level == 2) { // 当前是二级
        currentLevel = row.level;
        totalLevel = row.level;
        if (row.children && row.children.length > 0) {
          totalLevel = row.level + 1;
        }
        let oneItem = this.getAreaNodeData(row.parentId);
        name1 = oneItem && oneItem.name;
        area1 = oneItem;
        name2 = row.name;
        area2 = row;
      } else if (row.level == 1) { // 当前是1级
        currentLevel = row.level;
        totalLevel = row.level;
        if (row.children && row.children.length > 0) {
          totalLevel = row.level + 1;
          row.children.some(ent => {
            if (ent.children && ent.children.length > 0) {
              totalLevel = row.level + 2;
              return true;
            }
          });
        }
        name1 = row.name;
        area1 = row;
      }

      return {
          currentLevel: currentLevel, // 当前层级
          totalLevel: totalLevel, // 总层级
          name1: name1,
          area1: area1,
          name2: name2,
          area2: area2,
          name3: name3,
          area3: area3
        };
    },

  },
}
</script>


<style lang="scss" scoped>
.area-main {
  // ::v-deep .el-form-item--small .el-form-item__content {
  //   width: calc(100% - 100px);
  // }
  .area-bottom {
    display: flex;
    flex-direction: row;
    .dialog-left {
      margin-top: 8px;
      flex: 1;
      // background-color: red;
      display: flex;
      flex-direction: column;
      .left-area {
        display: inline-block;
        width: calc(100% - 25px);
        // width:100%;
        height: 260px;//300px;
        margin-top: 5px;
        margin-left: 10px;
        // margin-right: 25px;
        border: 1px solid #e5e6e7;
        background: #FFFFFF none;
        border-radius:4px;
        overflow: auto;
      }
    }
    .dialog-mid {
      display: inline-block;
      height: 363px;//403px;
      background-color: #EBEEF5;
      // background-color: red;
      margin-top: -4px;
      width: 1px;
    }
    .dialog-right {
      flex: 1;
      // background-color: orange;
      .right-top {
        margin-top: 14px;
        margin-left: 18px;
        margin-bottom: 30px;
        display: inline-block;
      }
      ::v-deep.el-table__header-wrapper {
        border: 0;
        height:0;
      }
      ::v-deep.el-table__cell {
        border: 0;
      }
      
      ::v-deep.el-table .cell {
        line-height: 28.5px;
      }
      .right-bottom {
        height: 272px;//312px;
        // margin-left: 18px;
        overflow: auto;
        // background-color: lightcoral;
        .table-column-area {
          margin-left: 10px;
          display: flex;
          flex-direction: row;
          justify-content: space-between;
          flex
          .table-column-area-span {
            // flex: 3;
            height: 28.5px;
            // padding-left: 40px;
            // margin-left: 50px;
            font-size: 14px;
            font-weight: 400;
          }
          
          .table-column-area-btn {
            // flex: 1;
          }
        }
      }
    }
  }

  .area-bottom-desc {
    background-color: #FEF6E7;
    height: 100px;
    width: 100%;
    border-radius: 4px;
    overflow: auto;
  }
}
</style>
